package com.bdc.whatwhat.task;

import android.os.AsyncTask;

import com.bdc.whatwhat.Service.Service;
import com.bdc.whatwhat.modele.WhatWhat;
import com.bdc.whatwhat.modele.Whatter;

import java.util.List;

/**
 * Created by florentchampigny on 25/06/14.
 */
public class RechercheUtilisateurTask extends AsyncTask<Object, Void, List<Whatter>> {

    public interface RechercheUtilisateurDelegate {
        public void afficherChargement(boolean afficher);

        public void onRechercheUtilisateurRecu(List<Whatter> whatters);

        public void onResultatVide();

        public void onErreurReseau();
    }

    RechercheUtilisateurDelegate delegate;
    boolean erreurReseau;
    boolean resultatVide;

    public RechercheUtilisateurTask(RechercheUtilisateurDelegate delegate) {
        this.delegate = delegate;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        if (delegate != null)
            delegate.afficherChargement(true);
    }

    @Override
    protected List<Whatter> doInBackground(Object... objects) {
        String phrase = (String) objects[0];
        Integer page = (Integer) objects[1];
        String token = (String) objects[2];

        List<Whatter> whatters = null;

        try {
            whatters = Service.rechercheUtilisateur(phrase, page, token);
        } catch (Service.NetworkException e) {
            erreurReseau = true;
            e.printStackTrace();
        }

        if (whatters == null || whatters.size() == 0)
            resultatVide = true;

        return whatters;
    }

    @Override
    protected void onPostExecute(List<Whatter> whatters) {
        super.onPostExecute(whatters);
        if (delegate != null) {
            delegate.afficherChargement(false);
            if (erreurReseau)
                delegate.onErreurReseau();
            else if (resultatVide)
                delegate.onResultatVide();
            else
                delegate.onRechercheUtilisateurRecu(whatters);
        }
    }
}
